﻿using System;
using System.Collections.Generic;
using System.Linq;
using UcAsp.Net.Model;

namespace UcAsp.Net.NOSQLDAL
{
    public class CommentsDAL : UcAsp.Net.IDAL.ICommentsDAL
    {
        public List<Comments> GetComments()
        {
            return STSData.GetInstance.Select<Model.Comments>();
        }

        public bool Insert(Comments model)
        {
            long key;
            Model.Comments lastrow = STSData.GetInstance.LastRow<Model.Comments>(out key);
            model.ID = Convert.ToInt32(key.ToString()) + 1;
            STSData.GetInstance.Insert<Model.Comments>(model.ID, model);
            return true;
        }

        public List<Comments> Select(int artid, int pageindex, int pagesize, out int pagecount)
        {
            IEnumerable<Comments> query = GetComments().Where(o => o.ParentID == 0);
            if (artid != 0)
            {
                query.Where(o => o.ArticleID == artid);
            }

            pagecount = (query.Count() / pagesize) + 1;
            query.OrderByDescending(o => o.PublicDate).Skip(pagesize * pageindex).Take(pagesize);

            List<Comments> result = new List<Comments>();
            foreach (Comments comments in query)
            {
                if (comments.ArticleID != 0)
                {
                    comments.Articles = new ArticlesDAL().GetArtces().FirstOrDefault(o => o.ID == comments.ArticleID);
                }
                else
                {
                    comments.Articles = new Articles();
                }
                result.Add(comments);
            }
            return query.ToList();
        }

        public bool Update(Comments model)
        {
            STSData.GetInstance.Update<Model.Comments>(model.ID, model);
            return true;
        }

        public bool Delete(Comments model)
        {
            STSData.GetInstance.Delete<Model.Comments>(model.ID);
            return true;
        }

        public Comments GetCommentsByID(int id)
        {
            return GetComments().FirstOrDefault(o => o.ID == id);
        }
    }
}